package com.heima.schedule.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.rediscache.RedisCacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;


@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {



    @Autowired
    private ThreadPoolTaskExecutor threaPool;

    /**
     * 添加延迟任务
     *
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {

        Future<Long> future = threaPool.submit(new Callable<Long>() {
            /**
             * Computes a result, or throws an exception if unable to do so.
             *
             * @return computed result
             * @throws Exception if unable to compute a result
             */
            @Override
            public Long call() throws Exception {

                //1.添加任务到数据库中

                boolean success = addTaskToDb(task);

                if (success) {
                    //2.添加任务到redis
                    addTaskToCache(task);

                }
                System.out.println("活动线程:" + threaPool.getActiveCount());
                //TODO 考虑当前task.getTaskId()是否有值？
                return task.getTaskId();

            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }




    /**
     * 按照类型和优先级拉取任务
     *
     * @return
     */
    @Override
    public Task poll(int type, int priority) {

        Future<Task> future = threaPool.submit(new Callable<Task>() {
            /**
             * Computes a result, or throws an exception if unable to do so.
             *
             * @return computed result
             * @throws Exception if unable to compute a result
             */
            @Override
            public Task call() throws Exception {

                Task task = null;
                try {
                    String key = type + "_" + priority;
                    String task_json = redisCacheService.lRightPop(ScheduleConstants.TOPIC + key);
                    if (StringUtils.isNotBlank(task_json)) {
                        task = JSON.parseObject(task_json, Task.class);

                        //修改数据库的表，删除任务表以及修改任务日志表的状态以及version
                        taskinfoMapper.deleteById(task.getTaskId());
                        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
                        if (taskinfoLogs != null) {
                            taskinfoLogs.setStatus(0);
                            taskinfoLogsMapper.updateById(taskinfoLogs);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("poll task exception");
                }
                //返回数据
                return task;
            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    @Autowired
    private RedisCacheService redisCacheService;

    /**
     * 把任务添加到redis中
     *
     * @param task
     */
    private void addTaskToCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        //2.1 如果执行时间小于当前时间，则存入list中
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            redisCacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        }
        //2.2如果执行时间大于当前时间，小于预设时间(当前时间+5分钟)，则存入zset中
        //获取预设时间=当前时间+5分钟
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        //获取当前时间的5分钟之后的毫秒值
        long fiveTime = calendar.getTimeInMillis();
        if (task.getExecuteTime() > System.currentTimeMillis() && task.getExecuteTime() <= fiveTime) {
            redisCacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }


    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        boolean flag = false;

        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        threaPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //加入休眠时间
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");

//        String token = redisCacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
//        if (StringUtils.isNotBlank(token)) {


                log.info("未来数据定时刷新---定时任务");

                // 获取所有未来数据集合的key值
                Set<String> futureKeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");// future_*
                for (String futureKey : futureKeys) { // future_250_250
                    //获取该组key下当前需要消费的任务数据
                    Set<String> tasks = redisCacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                    if (!tasks.isEmpty()) {
                        //获取toipcKey
                        String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                        //将这些任务数据添加到消费者队列中
                        String substring = futureKey.substring(7);
                        String listkey= ScheduleConstants.TOPIC+ substring;
                        redisCacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                        log.info("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                    }
                }
                }
        });
}

   //}


    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void rteloadDaa() {
        clearCache();
        log.info("数据库数据同步到缓存");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //查看小于未来5分钟的所有任务
        List<Taskinfo> allTask = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if (allTask != null && allTask.size() > 0) {
            for (Taskinfo taskinfo : allTask) {
                Task task =new Task();
                BeanUtils.copyProperties(taskinfo,task);
             task.setExecuteTime(taskinfo.getExecuteTime().getTime());
             addTaskToCache(task);
            }
        }
    }

    private void clearCache() {
        //删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> futurekeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topickeys = redisCacheService.scan(ScheduleConstants.TOPIC + "*");
        redisCacheService.delete(futurekeys);
        redisCacheService.delete(topickeys);
    }
}